﻿using log4net;
using log4net.Config;
using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp2
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public static ILog log = LogManager.GetLogger(typeof(MainWindow));

        private Dictionary<string, string> mCookies = new Dictionary<string, string>();//保存Cookie到字典中

        private String domain = ConfigurationManager.AppSettings["domain"];
        private String viewUri = ConfigurationManager.AppSettings["viewUrl"];
        private String loginUrl = ConfigurationManager.AppSettings["loginUrl"];
        private String cookieName = ConfigurationManager.AppSettings["cookieName"]; // 用于登录
        public MainWindow()
        {
            log.Debug("MainWindow Init.");
            InitializeComponent();

            #region 启动时串口最大化显示
            Rect rc = SystemParameters.WorkArea; //获取工作区大小
            this.Left = 0; //设置位置
            this.Top = 0;
            this.Width = rc.Width;
            this.Height = rc.Height;
            #endregion
        }

        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            log.Info("Window_Loaded.");

            await webView1.EnsureCoreWebView2Async();
           // webView1.CoreWebView2.OpenDevToolsWindow();

            webView1.NavigationCompleted += WebView1_login;
            log.Info("Loaded Url:." + loginUrl);
            webView1.Source = new Uri(loginUrl);
        }

        private async void WebView1_login(object sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            log.Info("WebView1_login start.");
            webView1.NavigationCompleted -= WebView1_login;

            await loginForm();


            log.Info("WebView1_login end.");
        }

        private async Task loginForm() {

            await Task.Delay(5000);

            this.webView1.CoreWebView2.ExecuteScriptAsync("$(\"[type='Password']\").val('1')");
            this.webView1.CoreWebView2.ExecuteScriptAsync("$(\"[name='AccountNumber']\").val('www')");
            this.webView1.CoreWebView2.ExecuteScriptAsync("$(\"#submitBtn\").click()");

            this.webView1.NavigationCompleted += WebView1_NavigationCompleted;
        }

        private void WebView1_NavigationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
        {
            log.Info("WebView1_NavigationCompleted start.");
            getCookie(domain);
            this.webView1.NavigationCompleted -= WebView1_NavigationCompleted;
            this.webView1.Visibility = Visibility.Hidden;

            foreach (var item in mCookies)
            {
                CoreWebView2Cookie cookie = webView2.CoreWebView2.CookieManager.CreateCookie(item.Key, item.Value, domain, "/");
                webView2.CoreWebView2.CookieManager.AddOrUpdateCookie(cookie);
                log.Info("cookie:  " + JsonConvert.SerializeObject(cookie));
            }

            this.webView2.Source = new Uri(viewUri);
            this.webView2.Visibility = Visibility.Visible;
            webView2.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;

            log.Info("WebView1_NavigationCompleted end.");
        }


        /// <summary>
        /// WebView2异步获取cookie
        /// </summary>
        /// <param name="url">与cookie关联的域名</param>
        private async void getCookie(string url)
        {
            List<CoreWebView2Cookie> cookieList = await webView1.CoreWebView2.CookieManager.GetCookiesAsync(url);
            mCookies.Clear();
            for (int i = 0; i < cookieList.Count; ++i)
            {
                CoreWebView2Cookie cookie = webView1.CoreWebView2.CookieManager.CreateCookieWithSystemNetCookie(cookieList[i].ToSystemNetCookie());
                mCookies.Add(cookie.Name, cookie.Value);
            }
            log.Info("cookie:  " + JsonConvert.SerializeObject(mCookies));
        }

    }
}
